package com.readen.leetcode;
/**
 * Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
 For example,
 Given n = 3,
 You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
 * 
 * @author Administrator
 *
 */

public class SpiralMatrix {

    public int[][] generateMatrix(int n) {
        int[][] result=new int[n][n];
    	int x=-1,y=0;
    	int dx=1,dy=0;
    	int count=0,total=n*n;
    	int pre=0;
    	while(count<total){
    		int c=(int) Math.sqrt(total-count);
    		for(int i=0;i<c;i++){
    			x+=dx;
				y+=dy;
				result[y][x]=++pre;
				count++;
			}
    		if(dx==1){
    			dx=0;
    			dy=1;
    			continue;
    		}
    		if(dy==1){
    			dx=-1;
    			dy=0;
    			continue;
    		}
    		if(dx==-1){
    			dx=0;
    			dy=-1;
    			continue;
    		}
    		if(dy==-1){	
    			dx=1;
    			dy=0;
    		}
    	}	
    	return result;
    }
	
	
}
